package com.xb.sourest.ui;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;

import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.Nullable;
import androidx.viewpager.widget.ViewPager;
import androidx.viewpager2.widget.ViewPager2;

import com.hyphenate.chat.EMClient;
import com.j256.ormlite.stmt.query.In;
import com.xb.sourest.MainActivity;
import com.xb.sourest.R;
import com.xb.sourest.adapter.VpAdapter;
import com.xb.sourest.base.BaseActivity;
import com.xb.sourest.im.HxSdkHelper;
import com.xb.sourest.storge.sp.Sp;
import com.xb.sourest.ui.login.LoginActivity;
import com.xd.navi.log.KLog;

import java.util.ArrayList;
import java.util.Map;

import butterknife.BindView;

public class SplashActivity extends BaseActivity {

    @BindView(R.id.img_viewpager)
    ViewPager viewPager;
    @BindView(R.id.dot_Layout)
    LinearLayout dot_Layout;

    private static  int[] imgs = {R.mipmap.first,R.mipmap.second,R.mipmap.third};
    private ArrayList<ImageView> imageViews;
    private ImageView[] dotViews;//小圆点

    private boolean mIsReLaunch;;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        //app首次安装完成后在安装界面直接“打开”应用再按home键返回桌面，重新进入app重复实例化launcher activity的问题解决方案
        //判断该Activity是不是任务空间的源Activity，“非”也就是说是被系统重新实例化出来
        if (!this.isTaskRoot()) {
            Intent mainIntent = getIntent();
            String action = mainIntent.getAction();
            if (mainIntent.hasCategory(Intent.CATEGORY_LAUNCHER) && action.equals(Intent.ACTION_MAIN))
                mIsReLaunch = true;
        }
        super.onCreate(savedInstanceState);
    }

    @Override
    protected int initLayoutRes() {
        return R.layout.activity_splash;
    }

    @Override
    protected void loadData() {
        if (mIsReLaunch) {
            finish();
            return;
        }
        requestPermission();
        //ToDo() 是否登录
        if (!Sp.getBoolean(SplashActivity.this,"isLogin",false)){
            initImageView();
            initDots();
            viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                @Override
                public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                    for(int i = 0; i < dotViews.length; i++)
                    {
                        dotViews[i].setImageResource(R.drawable.dot_selector);
                        if(position == i)
                        {
                            dotViews[i].setSelected(true);
                        }
                        else {
                            dotViews[i].setSelected(false);
                        }
                    }
                }

                @Override
                public void onPageSelected(int position) {
                    for(int i = 0; i < dotViews.length; i++) {
                        if(position == i) {
                            dotViews[i].setSelected(true);
                        } else {
                            dotViews[i].setSelected(false);
                        }
                    }
                }

                @Override
                public void onPageScrollStateChanged(int state) {

                }
            });
        }else {
            HxSdkHelper.getInstance().loadHxLocalData();
            skipIntent();
        }
    }

    private void initImageView() {

        //设置每一张图片都填充窗口
        ViewPager.LayoutParams mParams = new ViewPager.LayoutParams();
        imageViews = new ArrayList<ImageView>();
        for(int i=0; i< imgs.length; i++) {
            ImageView iv = new ImageView(this);
            iv.setLayoutParams(mParams);    //设置布局
            iv.setImageResource(imgs[i]);    //为ImageView添加图片资源
            iv.setScaleType(ImageView.ScaleType.FIT_XY);   //这里也是一个图片的适配
            imageViews.add(iv);
            if (i == imgs.length -1 ){
                iv.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //ToDo()这里的判断条件会变
                        if (HxSdkHelper.getInstance().canAutoLogin()) {
                            //       String curLoginUser = HxSdkHelper.getInstance().getCurLoginUser();
                            HxSdkHelper.getInstance().loadHxLocalData();
                            skipIntent();
                        }else {
                            Intent intent = new Intent(SplashActivity.this,LoginActivity.class);
                            startActivity(intent);
                        }
                    }
                });
            }
        }

        viewPager.setAdapter(new VpAdapter(imageViews));
    }

    //小圆点数量判断以及小圆点之间的间隔&小圆点默认启动显示的位置
    private void initDots(){
        LinearLayout layout = (LinearLayout)findViewById(R.id.dot_Layout);
        LinearLayout.LayoutParams mParams = new LinearLayout.LayoutParams(20, 20);
        mParams.setMargins(10, 0, 10,0);//设置小圆点左右之间的间隔
        dotViews = new ImageView[imgs.length];
        //判断小圆点的数量，从0开始，0表示第一个
        for(int i = 0; i < imageViews.size(); i++) {
            ImageView imageView = new ImageView(this);
            imageView.setLayoutParams(mParams);
            imageView.setImageResource(R.drawable.dot_selector);
            if(i== 0) {
                imageView.setSelected(true);//默认启动时，选中第一个小圆点
            } else {
                imageView.setSelected(false);
            }
            dotViews[i] = imageView;//得到每个小圆点的引用，用于滑动页面时，（onPageSelected方法中）更改它们的状态。
            layout.addView(imageView);//添加到布局里面显示
        }
    }



    @Override
    protected void upView() {

    }

    private void skipIntent() {
        Intent intent = new Intent(SplashActivity.this, MainActivity.class);
        startActivity(intent);
    }

    //androidx activity动态权限申请，省去了onActivityResult等操作男，同样适用于其他情况
    private void requestPermission() {
        registerForActivityResult(new ActivityResultContracts.
                RequestMultiplePermissions(), new ActivityResultCallback<Map<String, Boolean>>() {
            @Override
            public void onActivityResult(Map<String, Boolean> result) {

            }
        }).launch(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.WRITE_EXTERNAL_STORAGE
                , Manifest.permission.READ_CONTACTS, Manifest.permission.READ_SMS, Manifest.permission.READ_PHONE_STATE
                , Manifest.permission.CAMERA, Manifest.permission.CALL_PHONE});

    }

    @Override
    public void onBackPressed() {
        //不准后退
    }
}
